package com.samse.plzcallme;

import com.admob.android.ads.AdManager;
import com.admob.android.ads.AdView;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Settings extends Activity {
	public static final String TAG = "PlzCallMe";
	public static final int REQUESTID_CONTACT_PICKER = 0;
	public static final int REQUESTID_CONTACT_UPDATE = 0;
	
	Context mContext;
	String []mNumbers;
	int	mTotal;
	DatabaseHelper helper;
	ListView mList;
	Cursor mCursor;
	
	private static final int MAX_NUMBER = 10;
	private static final String TABLE_NAME = "plzcallme_settings";
	
	private int lastPosition;
	private long lastId;
	private LinearLayout mContent;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);

		mContext = this;

//		if(false) {		
//			// for AdMob test
//			AdManager.setTestDevices( 
//					new String[] { 
//							AdManager.TEST_EMULATOR,	
//							"E83D20734F72FB3108F104ABC0FFC738", // My T-Mobile G1 Test Phone
//			} );
//		}else {
//			AdView adView = (AdView)findViewById(R.id.ad);
//			adView.requestFreshAd();
//		}
		
		helper = new DatabaseHelper();
		
		Button btn = (Button)findViewById(R.id.add_number);
		btn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				addItem();
			}
		});

		mList = (ListView)findViewById(R.id.user_list);
		this.registerForContextMenu(mList);
		mList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				Log.d(TAG, "position : " + position + ", id=" + id);
				lastPosition = position;
				lastId = id;
				return false;
			}
		});
		
		mCursor = helper.getAllItem();

		SimpleCursorAdapter cs = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, mCursor,
                 new String[] { UserSettingProvider.PHONE_NUMBER, UserSettingProvider.MATCH_STRING }, 
                 new int[] { android.R.id.text1, android.R.id.text2 }); 
		mList.setAdapter(cs);
		
		restoreSharedPreferece();
		
//		SharedPreferences prefs = mContext.getSharedPreferences("pleaze_call_me", Activity.MODE_PRIVATE);
//	    int count = prefs.getInt("total_number", 0);
//	    Log.d(Settings.TAG, "Stored tel no's count is " + count);

	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)  {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==REQUESTID_CONTACT_PICKER) {
			if(resultCode==RESULT_OK) {
				Bundle bundle = data.getExtras();
				String mode = bundle.getString("mode");
				String new_number = bundle.getString("number");
				String match_string = bundle.getString("matchString");
				//Toast.makeText(this, "New no : " + new_number, Toast.LENGTH_SHORT).show();
				AlertDialog.Builder b = new AlertDialog.Builder(this);
				b.setMessage(getString(R.string.warn_message, new_number, match_string, new_number));
				b.setTitle(R.string.app_name);
				b.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
				});
				b.show();
				
				if(mode.equals("add")) {
					Log.d(TAG, "addItem : " + new_number + ", " + match_string);
					helper.addItem(new_number, match_string);
				}else {
					Log.d(TAG, "updateItem : " + new_number + ", " + match_string);
					helper.updateItem(lastId, new_number, match_string);
				}
				restoreSharedPreferece();
			}
		}else if(requestCode==REQUESTID_CONTACT_UPDATE) {
			
		}
	}
	
	/**
	 * 
	 */
	public void addItem() {
		Intent i = new Intent(mContext, ContactPicker.class);
		i.putExtra("isEditMode", false);
		startActivityForResult(i, REQUESTID_CONTACT_PICKER);
	}
	
	/**
	 * 
	 * @param position
	 * @return
	 */
	public boolean updateItem() {
		
		ItemInfo item = getItemInfoFromDB(lastPosition);
		Intent i = new Intent(mContext, ContactPicker.class);
		i.putExtra("isEditMode", true);
		i.putExtra("_ID", lastId);
		i.putExtra("phone_number", item.phone_number);
		i.putExtra("match_string", item.match_string);
		startActivityForResult(i, REQUESTID_CONTACT_UPDATE);
		return false;
	}
	
	/**
	 * 
	 * @param lastPosition2
	 * @return
	 */
	public boolean deleteItem() {
		if(helper.deleteItem(lastId)>0) {
			mCursor.requery();
			restoreSharedPreferece();
		}
		return false;
	}
	
	/**
	 * 
	 */
	public void deleteAll() {
		
	}
/*total_number
 *   number_xxx
 *   match_xxx
*/
	private void restoreSharedPreferece() {
		Log.d(TAG, "Restore SharedPreferences........");
		mCursor.requery();
		SharedPreferences prefs = mContext.getSharedPreferences("pleaze_call_me", Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = prefs.edit();
		String phone_number;
		String match_string;
		int index = 0;
		
		if(mCursor.moveToFirst()) {
			String item;
			int count = mCursor.getCount();
			editor.putInt("total_number", count);
			Log.d(TAG, "tatal_number : " + count);
			int _noIndex = mCursor.getColumnIndex(UserSettingProvider.PHONE_NUMBER);
			int _strIndex = mCursor.getColumnIndex(UserSettingProvider.MATCH_STRING);
			do {
				phone_number = mCursor.getString(_noIndex);
				match_string = mCursor.getString(_strIndex);
				item = "number_"+(index+1);
				Log.d(TAG, "add no : " + item + "=" + phone_number);
				editor.putString(item, phone_number);
				item = "match_"+(index+1);
				Log.d(TAG, "add str : " + item + "=" + match_string);
				editor.putString("match_" + (index+1), match_string);
				index++;
			}while(mCursor.moveToNext());
		}
		editor.commit();
	}

	private class ItemInfo {
		public String phone_number;
		public String match_string;
	}
	
	private ItemInfo getItemInfoFromDB(int pos) {
		ItemInfo i = new ItemInfo();
		long _ID = mList.getItemIdAtPosition(pos);
		long id;
		
		if(mCursor.moveToFirst()) {
			int _IdIndex = mCursor.getColumnIndex(UserSettingProvider._ID);
			int _noIndex = mCursor.getColumnIndex(UserSettingProvider.PHONE_NUMBER);
			int _strIndex = mCursor.getColumnIndex(UserSettingProvider.MATCH_STRING);
			do {
				id = mCursor.getLong(_IdIndex);
				if(id == _ID) {
					i.phone_number = mCursor.getString(_noIndex);
					i.match_string = mCursor.getString(_strIndex);
					break;
				}
			}while(mCursor.moveToNext());
		}

		return i;
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case CMENU_UPDATE:
			updateItem();
			break;
		case CMENU_DELETE:
			Log.d(TAG, "Delete caller");
			deleteItem();
			break;
		}
		return super.onContextItemSelected(item);
	}

	private static final int CMENU_UPDATE = 1000;
	private static final int CMENU_DELETE = 1001;
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.add(0, CMENU_UPDATE, 0, R.string.mnu_edit);
		menu.add(0, CMENU_DELETE, 0, R.string.mnu_delete);
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		return super.onOptionsItemSelected(item);
	}

	class DatabaseHelper {
		
		public Cursor getAllItem() {
			Uri allTitles = Uri.parse("content://com.samse.plzcallme.provider.Users/users");
			return managedQuery(allTitles, null, null, null, UserSettingProvider.PHONE_NUMBER);
		}
		
		public Uri addItem(String no, String str) {
			ContentValues values = new ContentValues();
			values.put(UserSettingProvider.MATCH_STRING, str);
			values.put(UserSettingProvider.PHONE_NUMBER, no);
			
			try {
				Cursor c = getContentResolver().query(UserSettingProvider.CONTENT_URI, 
						null, //new String[]{UserSettingProvider.PHONE_NUMBER, UserSettingProvider.MATCH_STRING}, 
						UserSettingProvider.PHONE_NUMBER + "='" + no + "'" //+ " and " + 
//						UserSettingProvider.MATCH_STRING + "='" + str + "'",
						,null, UserSettingProvider.PHONE_NUMBER);
				if(c.moveToNext()) {
					Log.d(TAG, "aleady exist: " + no + ", " + str);
					return null;
				}
				
				Uri uri = getContentResolver().insert(UserSettingProvider.CONTENT_URI, values);
				return uri;
			}catch(SQLiteException e) {
				Log.d(TAG, "Exception: addItem");
				e.printStackTrace();
				return null;
			}
		}
		
		public void updateItem(long _id, String number, String string) {
			ContentValues values = new ContentValues();
			values.put(UserSettingProvider.MATCH_STRING, string);
			values.put(UserSettingProvider.PHONE_NUMBER, number);
			String query = "_ID=" + _id;
			Log.d(TAG, "updateitem query =" + query);
			getContentResolver().update(UserSettingProvider.CONTENT_URI, values, query, null);
		}
		
		public int deleteItem(long _id) {
			return getContentResolver().delete(UserSettingProvider.CONTENT_URI, "_ID="+_id, null);
		}
	}
	
}
	